package com.hxb.example.chatModel.openapi.config.funcation;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.hxb.example.properties.GaodeProperties;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Description;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.function.Function;

@Slf4j
@Component
@Description("这是一个获取地理位置坐标的function，调用高德地图根据名称获取具体经纬度")
public class CoordinateFunction implements Function<CoordinateFunction.Request, CoordinateFunction.Response> {

    @Resource
    private GaodeProperties gaodeProperties;
    @Resource
    private RestTemplate restTemplate;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonClassDescription("Weather API request")
    public record Request(@JsonProperty(required = true, value = "区域编码")
                          @JsonPropertyDescription("区域编码，例如: 110101") String adcode) {
    }

    public record Response(String weather) {
    }

    @Override
    public Response apply(Request request) {
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("key", gaodeProperties.getKey());
        params.add("city", request.adcode);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(gaodeProperties.getWeatherUrl());
        URI uri = builder.queryParams(params).build().encode().toUri();

        JSONObject jsonObject = restTemplate.getForObject(uri, JSONObject.class);
        log.info("天气情况, param: {}: result: {}", request.adcode, jsonObject);
        assert jsonObject != null;
        if (jsonObject.getIntValue("status") == 1) {
            return new Response(jsonObject.getString("lives"));
        }
        return null;
    }
}
